package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.CheckoutUtil;
import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.app.util.WeiXinUtil;
import cn.wolfcode.trip.base.domain.OAuthInfo;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@Controller
public class WechatLogin {
    @Autowired
    private IUserService userService;
    /**
     * 微信消息接收和token验证
     * @param model
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/ownerCheck")
    public void ownerCheck(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println(111);
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        PrintWriter print;
        if (isGet) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && CheckoutUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    print = response.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 微信引导页进入的方法
     * @return
     */
    @RequestMapping("/loginByWeiXin")
    public String loginByWeiXin(HttpServletRequest request,HttpServletResponse response, Map<String, Object> map) {
        // 微信接口自带 2 个参数
        String code = request.getParameter("code");
        String uuidState = request.getParameter("state");
        System.out.println("code = " + code + ", state = " + uuidState);
        String uuid=request.getParameter("uuid");

        if(code != null && !"".equals(code)) {
            // 通过应用获取共享的uuid集合
            Map uuidMap = (Map) request.getServletContext().getAttribute("UUID_MAP");
            // 授权成功, 微信获取用户openID
            OAuthInfo authInfo = WeiXinUtil.getAccess_token(code);
            String openid = authInfo.getOpenid();
            String access_token = authInfo.getAccess_token();
            //获取微信用户信息
            /*String userInfo = WeiXinUtil.getUserInfo(authInfo);*/
            if(access_token == null) {
                // Code 使用过 异常
                System.out.println("Code 使用过 异常.....");
                return "redirect:" + WeiXinUtil.getStartURLToGetCode(uuidState);
            }
            //根据openId查询用户信息
            User user = userService.getUserInfoByOpenId(openid);
            if(user==null){//未绑定，跳转到注册页面
                return "/noBinded.html";
            }
            UserContext.setCurrentUser(user);
            // 如果集合内没有这个uuid，将这个uuid共享出去
            uuidMap.put(uuidState,user);
            /*uuidMap.put("user",user);*/
            // 登录成功
            return "/WXloginMsg.html";
        }
        // 未授权 获取code
        return "redirect:" + WeiXinUtil.getStartURLToGetCode(uuid);
    }

    /**
     * 账号绑定微信
     */
    @RequestMapping("/bindWechat")
    public String bindWechat(HttpServletRequest request,HttpServletResponse response, Map<String, Object> map){
        // 微信接口自带 2 个参数
        String code = request.getParameter("code");
        String userIdState = request.getParameter("state");
        System.out.println("code = " + code + ", state = " + userIdState);
        String uuid=request.getParameter("uuid");
        String userIdStr=request.getParameter("userId");
        if(code != null && !"".equals(code)) {
            // 通过应用获取共享的uuid集合
            Map uuidMap = (Map) request.getServletContext().getAttribute("UUID_MAP");
            // 授权成功, 微信获取用户openID
            OAuthInfo authInfo = WeiXinUtil.getAccess_token(code);
            String openid = authInfo.getOpenid();
            Boolean bindedWx = userService.isBindedWx(openid);
            //查询该账号是否已经绑定了微信
            User u=userService.getUserInfoById(Long.parseLong(userIdState));
            if(u.getOpenId()!=null&&openid.equals(u.getOpenId())){//您已经绑定过该账号了，无需再绑定！
                return "/binded.html";
            }
            if(bindedWx==false){//此微信还未绑定过任何账号的
                if(u.getOpenId()!=null){//该账号已被其他微信号所绑定！
                    return "/bindFail.html";
                }
                userService.bindWechat(openid,Long.parseLong(userIdState));
                return "/bindSuccess.html";
            }else{//该微信号已经绑定过其他账号了
                return "/binded2.html";
            }
        }
        // 未授权 获取code
        return "redirect:" + WeiXinUtil.getStartURLToGetCodeForBind(userIdStr);
    }
}
